package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.AuthConstant;
import com.atguigu.entity.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //解锁库存时查看订单状态时不是浏览器发过来的请求，不带用户登录信息
        //这些请求不需要做登录拦截
        String requestURI = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/order/order/status/**", requestURI);
        //支付回调的不用登录
        boolean match1 = new AntPathMatcher().match("/payed/notify/**", requestURI);

        if (match || match1){
            return true;
        }

        HttpSession session = request.getSession();
        MemberResponseVo user = (MemberResponseVo) session.getAttribute(AuthConstant.LOGIN_USER);
        if (user != null){
            //放在ThreadLocal中，以后其他线程都可以获取
            loginUser.set(user);

            return true;
        }else {
            session.setAttribute("msg","请先登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
